"""
Simple integration utilities for connecting monitoring to react_terminal
Loosely coupled design - minimal changes to existing code
"""

import threading
import time
from typing import Optional
from monitor_server import get_monitor

class MonitorIntegration:
    """Helper class for easy monitoring integration with react_terminal"""

    def __init__(self, auto_start: bool = True, port: int = 8000):
        self.monitor = get_monitor()
        self.auto_start = auto_start
        self.port = port
        self.server_thread = None
        self.connected_agent = None

    def start_monitor_server(self, host: str = "0.0.0.0"):
        """Start the monitoring server"""
        if self.server_thread is not None:
            print(f"Monitor server already running on port {self.port}")
            return

        from monitor_server import start_monitor_server
        self.monitor, self.server_thread = start_monitor_server(host=host, port=self.port)
        print(f"Monitor server started at http://localhost:{self.port}")

    def connect_agent(self, agent):
        """Connect an agent's memory to the monitor"""
        if hasattr(agent, 'memory'):
            self.monitor.connect_agent_memory(agent.memory)
            self.connected_agent = agent
            print(f"Connected agent memory to monitor")
        else:
            print("Error: Agent has no 'memory' attribute")

    def disconnect_agent(self):
        """Disconnect current agent from monitor"""
        self.monitor.disconnect_agent_memory()
        self.connected_agent = None
        print("Disconnected agent from monitor")

    def record_event(self, event_type: str = "update"):
        """Record an event in the monitor"""
        self.monitor.record_state(event_type)

    def get_status(self):
        """Get monitor status"""
        return {
            "server_running": self.server_thread is not None,
            "agent_connected": self.connected_agent is not None,
            "port": self.port,
            "timeline_length": len(self.monitor.memory_history)
        }

# Global monitor integration instance
_monitor_integration = None

def get_monitor_integration(auto_start: bool = True, port: int = 8000) -> MonitorIntegration:
    """Get the global monitor integration instance"""
    global _monitor_integration
    if _monitor_integration is None:
        _monitor_integration = MonitorIntegration(auto_start=auto_start, port=port)
        if auto_start:
            _monitor_integration.start_monitor_server()
    return _monitor_integration

def connect_agent_to_monitor(agent, port: int = 8000):
    """Convenience function to connect an agent to monitoring"""
    monitor_integration = get_monitor_integration(port=port)
    monitor_integration.connect_agent(agent)
    return monitor_integration

def setup_monitoring_for_terminal(port: int = 8000):
    """Setup monitoring for use with react_terminal"""
    """
    Usage in react_terminal:

    # Import the monitoring setup
    from monitor_integration import setup_monitoring_for_terminal

    # Start monitoring server
    monitor_integration = setup_monitoring_for_terminal(port=8000)

    # Create your agent as usual
    agent = ReActAgent(tools_system=GLOBAL_TOOL_SYSTEM, ...)

    # Connect agent to monitor
    monitor_integration.connect_agent(agent)

    # Now you can use the agent normally, and it will be monitored
    # The web interface will be available at http://localhost:8000

    # You can also record custom events
    monitor_integration.record_event("custom_event")

    # When done, disconnect
    monitor_integration.disconnect_agent()
    """
    return get_monitor_integration(port=port)

if __name__ == "__main__":
    # Test the integration
    print("Testing monitor integration...")

    integration = setup_monitoring_for_terminal(port=8001)
    print(f"Monitor integration ready on port 8001")
    print(f"Status: {integration.get_status()}")

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\nShutting down...")